<?php

namespace app\api\controller;

use think\Db;
use app\api\model\UserCertification;
use app\api\model\User;
use app\service\UserRepeat;
use app\service\BaiduApi;
use app\service\FaceAuth;

class Auth extends Common
{
    public function lists()
    {
        $contain = [
            // 'voice_auth' => 'voice',
            'is_identity_authentication' => 'real_auth',
            'realname_auth' => 'name_auth',
            'is_education_authentication' => 'education_auth',
            'car_auth' => 'car_auth',
            'house_auth' => 'house_auth',
            'income_auth' => 'income_auth',
            'marry_auth' => 'marry_auth',
            'phone' => 'phone_auth',
            'case_auth'=>'case_auth',
            // 'institutional_auth'=>'institutional_auth',
            // 'practitioner_auth'=>'practitioner_auth',
            'doctor_auth'=>'doctor_auth',
        ];

        $types = [
            'name_auth' => 1,
            'education_auth' => 2,
            'car_auth' => 3,
            'house_auth' => 4,
            'voice' => 5,
            'case_auth' => 6,
            // 'institutional_auth' => 7,
            // 'practitioner_auth' => 8,
            'doctor_auth' => 9,
            'income_auth' => 10,
            'marry_auth' => 11,
        ];

        $data = Db::name('task')->field('id, name, title, icon, reward')->where(['name' => ['in', $contain], 'channel'=>1])->order('sort desc, id asc')->select();
        $user = Db::name('user')->find(input('user_id'));
        // if(input('user_id') != $this->member['id']) {
        //     return $this->pass([]);
        // }
        foreach ($data as $key => $item) {
            $data[$key]['types'] = $item['types'] = $types[$item['name']] ?? '';
            $msg = ['', '实名', '学历', '车辆', '房产', '', '经验', '机构', '从业者', '专业', '收入', '婚姻'];
            if (in_array($item['name'], ['case_auth', 'institutional_auth', 'practitioner_auth', 'doctor_auth'])) {
                $data[$key]['status'] = 0;
                if ($item['name'] == 'institutional_auth') {
                    $data[$key]['status'] = Db::name('user_attestation')->where(['user_id'=>$this->member['id'], 'types'=>4])->count();
                } else if ($item['name'] == 'doctor_auth') {
                    // $data[$key]['status'] = Db::name('user_attestation')->where(['user_id'=>$this->member['id'], 'types'=>1])->count();
                    $data[$key]['remark'] = '可以提供任何能证明你这方面比较专业的截图（如：学历，证书，职称，入职，第三方平台截图等等）提供给我平台审核';
                } else if ($item['name'] == 'case_auth') {
                    $data[$key]['remark'] = '可以提供任何能证明你经历过这方面截图（如：景点门票，发票，第三方平台的截图，消费单等等）提供给我平台审核';
                }
                if ($user['is_identity_authentication'] != 2 && $user['realname_auth'] != 2) {
                    $data[$key]['data'] = [
                        'content' => '通过真人认证后，才能进行' . $msg[$item['types']] . '认证哦~',
                        'desc' => '立即真人认证',
                        'name' => 'real_auth',
                        'types' => '',
                        'status' => $user['is_identity_authentication']
                    ];
                } else if ($user['realname_auth'] != 2) {
                    $data[$key]['data'] = [
                        'content' => '通过实名认证后，才能进行' . $msg[$item['types']] . '认证哦~',
                        'desc' => '立即实名认证',
                        'name' => 'name_auth',
                        'types' => 1,
                        'status' => $user['realname_auth']
                    ];
                }
                $rzs = ['6'=>2,'7'=>4,'8'=>5,'9'=>1];
                $data[$key]['rz_types'] = $rzs[$data[$key]['types']];
                continue;
            }
            if ($item['name'] != 'phone_auth') {
                $field = array_search($item['name'], $contain);

                $status = $user[$field];
            } else {
                $status = $user['phone'] ? 2 : 0;
            }

            $data[$key]['status'] = $status;

            $data[$key]['reward'] = $status != 2 ? $item['reward'] : 0;

            $data[$key]['icon'] = changeUrl($item['icon']);
            $data[$key]['data'] = (object)[];

            if ($item['types'] == 1) {
                if ($user['is_identity_authentication'] != 2) {
                    $data[$key]['data'] = [
                        'content' => '通过真人认证后，才能进行' . $msg[$item['types']] . '认证哦~',
                        'desc' => '立即真人认证',
                        'name' => 'real_auth',
                        'types' => '',
                        'status' => $user['is_identity_authentication']
                    ];
                }
            } else if (in_array($item['types'], [2, 3, 4, 10, 11])) {
                if ($user['is_identity_authentication'] != 2 && $user['realname_auth'] != 2) {
                    $data[$key]['data'] = [
                        'content' => '通过真人认证后，才能进行' . $msg[$item['types']] . '认证哦~',
                        'desc' => '立即真人认证',
                        'name' => 'real_auth',
                        'types' => '',
                        'status' => $user['is_identity_authentication']
                    ];
                } else if ($user['realname_auth'] != 2) {
                    $data[$key]['data'] = [
                        'content' => '通过实名认证后，才能进行' . $msg[$item['types']] . '认证哦~',
                        'desc' => '立即实名认证',
                        'name' => 'name_auth',
                        'types' => 1,
                        'status' => $user['realname_auth']
                    ];
                }
            }
        }

        return $this->pass($data);
    }

    public function certification()
    {
        if ($this->member['reg'] != 1) return $this->miss('请重启APP再次尝试');
        $cachekey = 'certification:'. $this->member['id'];
        if (cache($cachekey)) {
            return $this->miss('提交过快，请稍后再试');
        } else {
            cache($cachekey, 1, 3);
        }
        $msg = ['', '实名', '学历', '车辆', '房产', '收入', '婚姻','真人'];
        $contain = ['', 'realname_auth', 'is_education_authentication', 'car_auth', 'house_auth', 'voice_auth', 'income_auth', 'marry_auth'];

        // if ($this->params['types'] == 1) {
        //     if ($this->member['is_identity_authentication'] != 2) {
        //         return $this->miss('通过真人认证后，才能进行' . $msg[$this->params['types']] . '认证哦~');
        //     }
        // } else if (in_array($this->params['types'], [2, 3, 4])) {
        //     if ($this->member['is_identity_authentication'] != 2 && $this->member['realname_auth'] != 2) {
        //         return $this->miss('通过真人认证和实名认证后，才能进行' . $msg[$this->params['types']] . '认证哦~');
        //     } else if ($this->member['realname_auth'] != 2) {
        //         return $this->miss('通过实名认证后，才能进行' . $msg[$this->params['types']] . '认证哦~');
        //     }
        // }
        if (in_array($this->params['types'], [2, 3, 4,5,6,7,8])) {
            if ($this->member['is_identity_authentication'] != 2 && $this->member['realname_auth'] != 2) {
                return $this->miss('只有先通过实名认证和真人认证后，才能进行' . $msg[$this->params['types']] . '认证哦~');
            } else if ($this->member['realname_auth'] != 2) {
                return $this->miss('通过实名认证后，才能进行' . $msg[$this->params['types']] . '认证哦~');
            }
        }

        $certification = Db::name('user_certification')->master()->where([
            'types' => $this->params['types'],
            'user_id' => $this->params['user_id']
        ])->find();

        $this->params['create_time'] = $this->params['update_time'] = time();

        if ($certification) {
            if ($certification['status'] == 0) {
                return $this->return['user.error.checkAuth'];
            }

            if ($certification['status'] == 1) {
                return $this->return['user.error.passAuth'];
            }

            $this->params['id'] = $certification['id'];
            $this->params['status'] = 0;
            $this->params['create_time'] = time();

            $method = 'update';
        } else {
            $method = 'create';
        }
        $state = 1;
        if($this->params['types'] == 1){
            $idcardPath = 'http://'.getenv('OSS_DOMAIN') . $this->params['image_front'];
            try {
                $ocrRes = BaiduApi::idcardOCR($idcardPath);
            } catch (\Exception $e) {
                $ocrRes = false;
            }
            if (!$ocrRes) {
                // $state = 0;
            } else {
                $hasNumber = Db::name('user_certification')->where(['user_id'=>['<>', $this->params['user_id']], 'data'=>$ocrRes['number']])->find();
                if ($hasNumber) {
                    $this->params['data_cover'] = $ocrRes['number'];
                    // $state = 0;
                } else {
                    if (!$certification || !$certification['data']) {
                        $this->params['data'] = $ocrRes['number'];
                        $this->params['data2'] = $ocrRes['name'];
                    }
                }
            }
            UserRepeat::InsertS($this->params['user_id'], 'idcards', $this->params['image_front'] . ',' . $this->params['image_behind']);

            $authimg = Db::name('auth')->where(['user_id'=>$this->params['user_id']])->value('image1');
            if ($authimg) {
                $authimg = strpos($authimg, 'http') === false ? 'http://'.getenv('OSS_DOMAIN') . $authimg : $authimg;
                $result = (new FaceAuth)->comparebaidu($authimg, $idcardPath);
                if ($result) {
                    $this->params['tip_reason'] = 1;
                } else if ($certification && $certification['tip_reason'] == 1) {
                    $this->params['tip_reason'] = 0;
                }
            }
        }


        User::update([
            'id' => $this->params['user_id'],
            $contain[$this->params['types']] => $state
        ]);

        UserCertification::$method($this->params);

        return $this->return['common.success.submit'];
    }

    public function detail()
    {
        // 1手机 | 2真人 | 3实名 | 4学历 | 5车辆 | 6房产

        $data = [];

        switch($this->params['types']) {
            case 1: // 手机
                if ($this->member['phone']) {
                    $data = [
                        'phone' => substr($this->member['phone'], 0, 3) . '****' . substr($this->member['phone'], 7, 4),
                        'date' => date('Y年m月d日', strtotime($this->member['register_datetime']))
                    ];
                }
                break;
            case 2: // 真人
                if ($this->member['is_identity_authentication'] == 2) {
                    $create_time = Db::name('auth')->where(['user_id' => $this->member['id']])->value('create_time');
                    $data = [
                        'date' => date('Y年m月d日', strtotime($create_time))
                    ];
                }
                break;
            case 3: // 实名
                if ($this->member['realname_auth'] == 2) {
                    $update_time = Db::name('user_certification')->where(['types' => 1, 'user_id' => $this->member['id'], 'status' => 1])->value('update_time');
                    $data = [
                        'date' => date('Y年m月d日', strtotime($update_time))
                    ];
                }
                break;
            case 4: // 学历
                if ($this->member['is_education_authentication'] == 2) {
                    $update_time = Db::name('user_certification')->where(['types' => 2, 'user_id' => $this->member['id'], 'status' => 1])->value('update_time');
                    $data = [
                        'date' => date('Y年m月d日', strtotime($update_time))
                    ];
                }
                break;
            case 5: // 车辆
                if ($this->member['car_auth'] == 2) {
                    $update_time = Db::name('user_certification')->where(['types' => 3, 'user_id' => $this->member['id'], 'status' => 1])->value('update_time');
                    $data = [
                        'date' => date('Y年m月d日', strtotime($update_time))
                    ];
                }
                break;
            case 6: // 房产
                if ($this->member['house_auth'] == 2) {
                    $update_time = Db::name('user_certification')->where(['types' => 4, 'user_id' => $this->member['id'], 'status' => 1])->value('update_time');
                    $data = [
                        'date' => date('Y年m月d日', strtotime($update_time))
                    ];
                }
                break;
        }

        return $this->pass($data);
    }
}
